﻿using Microsoft.AspNetCore.Http;
using Vin.Extension.ServerSentEvent.Client;
using Vin.Extension.ServerSentEvent.Options;
using Vin.Tool.AspNetCore.Singleton;

namespace Vin.Extension.ServerSentEvent;

public class VinBeforeSseMiddleware(RequestDelegate next) : IVinBeforeMiddlewareExtension
{
    public async Task Invoke(HttpContext context)
    {
        var sseOption = VinApp.GetOption<SseOption>();
        if (context.Request.Path != sseOption.Path)
        {
            await next(context);
            return;
        }

        string? serviceKey = null;
        if (context.Request.Query.ContainsKey(sseOption.ServiceQueryKey))
        {
            serviceKey = context.Request.Query[sseOption.ServiceQueryKey];
        }

        var client = VinApp.GetServiceByHttpContext<ISseClientAdapter>(serviceKey);
        if (client != null)
        {
            SseClientInstance.AddClient(client);

            await client.HandleAsync();

            SseClientInstance.RemoveClient(client);

            return;
        }
        
        // 返回 404
        context.Response.StatusCode = 404;
        await context.Response.WriteAsync("未找到对应的 SSE 服务");


        // var adapterList = SseClientInstance.Match(context);
        // if (adapterList.Count > 0)
        // {
        //     SseClient client = new(context);
        //     await client.InitAsync();
        //
        //     SseClientInstance.AddClient(client);
        //
        //     var adapterHandleList = new List<Task>();
        //
        //     foreach (var adapter in adapterList)
        //     {
        //         adapterHandleList.Add(adapter.HandleAsync(client));
        //     }
        //
        //     await Task.WhenAll(adapterHandleList);
        //
        //     SseClientInstance.RemoveClient(client);
        //
        //     return;
        // }

        await next(context);
    }
}